package com.xcm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xcm.config.CustomProperties;
import com.xcm.constant.BusinessConstant;
import com.xcm.constant.FileConstant;
import com.xcm.exception.ServiceException;
import com.xcm.model.TbProgramJsonAuthFailDetail;
import com.xcm.model.dto.BottomProgramDTO;
import com.xcm.model.dto.TopProgramDTO;
import com.xcm.service.*;
import com.xcm.util.ValidateProgramJsonUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 消息接收者
 *
 * @author linqiang
 * @date 2018-07-03 17:01
 */
@Service("programJsonAuthService")
public class ProgramJsonAuthServiceImpl implements ProgramJsonAuthService {
    private static final Logger logger = LoggerFactory.getLogger(ProgramJsonAuthServiceImpl.class);
    @Autowired
    private ProgramTopService programTopService;
    @Autowired
    private ProgramBottomService programBottomService;
    @Autowired
    private ProgramJsonService programJsonService;
    @Autowired
    private ProgramJsonAuthFailDetailService programJsonAuthFailDetailService;
    @Autowired
    private CustomProperties customProperties;

    /**
     * 接收队列的消息并验证
     *
     * @param xcVersion 节目版本号
     */
    @Async
    @Override
    public void auth(String xcVersion) {
        logger.info("ProgramJsonAuthServiceImpl auth 节目(版本：" + xcVersion + "校验开始)");
        //文件不存在
        StringBuilder fileNotFoundSb = new StringBuilder();
        //视频时长不合法
        StringBuilder videoDurationIllegalSb = new StringBuilder();
        //文件名为空
        StringBuilder fileNameIsNullSb = new StringBuilder();
        //文件URL为空
        StringBuilder fileURLIsNullSb = new StringBuilder();
        //视频时长为空
        StringBuilder videoDurationIsNullSb = new StringBuilder();
        // 文件下载临时存储目录
        String fileDownloadTempStoreDir = customProperties.getFileDownloadTempStoreDir();
        if (StringUtils.isBlank(xcVersion)) {
            return;
        }
        //上屏节目列表
        List<TopProgramDTO> topList = programTopService.listTopProgramDTOByXcVersion(xcVersion);
        //下屏节目列表
        List<BottomProgramDTO> bottomList = programBottomService.listBottomProgramDTOByXcVersion(xcVersion);
        //校验上下屏节目
        Map<String, Integer> msgMap = ValidateProgramJsonUtils.validateProgram(xcVersion, topList, bottomList, fileDownloadTempStoreDir);
        //返回信息map的size大于0，校验不通过
        if (msgMap.size() > 0) {
            programJsonService.updateProgramJsonAuthByXcVersion(BusinessConstant.PROGRAMJSON_AUTH_STATE_FAIL, xcVersion);
            for (Map.Entry<String, Integer> entry : msgMap.entrySet()) {
                int value = entry.getValue();
                String key = entry.getKey();
                //文件不存
                if (FileConstant.FILE_NOT_FOUND == value) {
                    if (fileNotFoundSb.length() > 0) {
                        fileNotFoundSb.append(",");
                    }
                    fileNotFoundSb.append(key);
                }
                //视频时长不合法
                if (FileConstant.VIDEO_DURATION_ILLEGAL == value) {
                    if (videoDurationIllegalSb.length() > 0) {
                        videoDurationIllegalSb.append(",");
                    }
                    fileNotFoundSb.append(key);
                }
                //文件名为空
                if (FileConstant.FILE_NAME_IS_NULL == value) {
                    if (fileNameIsNullSb.length() > 0) {
                        fileNameIsNullSb.append(",");
                    }
                    fileNameIsNullSb.append(key);
                }
                //文件URL地址为空
                if (FileConstant.FILE_URL_IS_NULL == value) {
                    if (fileURLIsNullSb.length() > 0) {
                        fileURLIsNullSb.append(",");
                    }
                    fileURLIsNullSb.append(key);
                }
                //视频时长为空
                if (FileConstant.VIDEO_DURATION_IS_NULL == value) {
                    if (videoDurationIsNullSb.length() > 0) {
                        videoDurationIsNullSb.append(",");
                    }
                    videoDurationIsNullSb.append(key);
                }
            }
            //保存验证不通过的详情
            TbProgramJsonAuthFailDetail programJsonAuthFailDetail = new TbProgramJsonAuthFailDetail();
            programJsonAuthFailDetail.setXcVersion(xcVersion);
            JSONObject jsonObject = new JSONObject();
            if (fileNotFoundSb.length() > 0) {
                jsonObject.put(BusinessConstant.VALIDATE_PROGRAM_FILE_NOT_FOUND, fileNotFoundSb.toString());
            }
            if (videoDurationIllegalSb.length() > 0) {
                jsonObject.put(BusinessConstant.VALIDATE_PROGRAM_VIDEO_DURATION_ILLEGAL, videoDurationIllegalSb.toString());
            }
            if (fileNameIsNullSb.length() > 0) {
                String fileNameIsNull = fileNameIsNullSb.toString();
                jsonObject.put(fileNameIsNull, "");
            }
            if (fileURLIsNullSb.length() > 0) {
                jsonObject.put(BusinessConstant.VALIDATE_PROGRAM_FILE_URL_IS_NULL, fileURLIsNullSb.toString());
            }
            if (videoDurationIsNullSb.length() > 0) {
                jsonObject.put(BusinessConstant.VALIDATE_PROGRAM_VIDEO_DURATION_IS_NULL, videoDurationIsNullSb.toString());
            }
            programJsonAuthFailDetail.setAuthFailDetail(jsonObject.toJSONString());
            programJsonAuthFailDetail.setAddTime(System.currentTimeMillis());
            try {
                programJsonAuthFailDetailService.saveProgramJsonAuthFailDetail(programJsonAuthFailDetail);
            } catch (ServiceException e) {
                e.printStackTrace();
                logger.error("ProgramJsonAuthServiceImpl auth 保存节目json校验失败详情失败；" + e.getMessage());
            }
        } else {
            //校验成功
            programJsonService.updateProgramJsonAuthByXcVersion(BusinessConstant.PROGRAMJSON_AUTH_STATE_SUCESS, xcVersion);
            logger.info("ProgramJsonAuthServiceImpl auth 节目(版本:" + xcVersion + ")校验成功");
        }
        //校验完后，删除文件目录及目录下的所有文件
        fileDownloadTempStoreDir = customProperties.getFileDownloadTempStoreDir();
        String separator = File.separator;
        if (fileDownloadTempStoreDir.endsWith(separator)) {
            fileDownloadTempStoreDir = fileDownloadTempStoreDir + xcVersion;
        } else {
            fileDownloadTempStoreDir = fileDownloadTempStoreDir + separator + xcVersion;
        }
        File tempFile = new File(fileDownloadTempStoreDir);
        if (tempFile.exists()) {
            try {
                FileUtils.deleteDirectory(tempFile);
            } catch (IOException e) {
                logger.error("ProgramJsonAuthServiceImpl auth 节目(版本:" + xcVersion + ")校验失败: " + e.getMessage());
            }
        }
    }
}
